/**
 * 样例代码
 */

//-----------------------------------------
// java 注入的依赖服务,无需初始化 (assembly.xml中定义)
//------------------------------------------  
var toDoItemRepository;
var scriptEngine;

//--------------------------------------
// java 注入的常规服务,无需初始化
//--------------------------------------
var assembly 
var assemblyConfig
var serviceRepository

//--------------------------------------
//java 类型
//--------------------------------------
var DefaultGraphQLModular = Java.type("com.massyframework.beanskin.graphql.context.DefaultGraphQLModular");
//运行植入工厂
var RuntimeWiringFactory = Java.type("com.massyframework.beanskin.graphql.context.RuntimeWiringFactory");
//运行植入器
var RuntimeWiring = Java.type("graphql.schema.idl.RuntimeWiring");
// 数据获取器
var DataFetcher = Java.type("graphql.schema.DataFetcher");
// GraphQL工具类
var GraphQLUtils = Java.type("com.massyframework.beanskin.graphql.util.GraphQLUtils");
// 表达式断言
var ExpressionPredicate = Java.type("com.massyframework.beanskin.graphql.util.expression.ExpressionPredicate");

var ToDoItem = Java.type("com.massyframework.beanskin.sample.ToDoItem");
var System = Java.type("java.lang.System");

/**
 * 按id查找待办事项
 */
var FindByIdDataFetcher = Java.extend(DataFetcher, {
	get: function(env){
		var id = env.getArgument("id");
		return toDoItemRepository.findById(id);
	}
});

/**
 * 所有待办事项
 */
var ItemsDataFetcher = Java.extend(DataFetcher, {
	get: function(env){
		System.out.println("recive request 2345.");
		console.log("hello");
		if (GraphQLUtils.fieldNameEquals(env.getFieldDefinition(), "getItemsWithExpression")){
			var filter = ExpressionPredicate.newInstance(env, "exp", scriptEngine, ToDoItem);
			return toDoItemRepository.getToDoItems(filter);
		}
		return toDoItemRepository.getToDoItems();
	}
});

//运行植入工厂类
var MyRuntimeWiringFactory = Java.extend(RuntimeWiringFactory, {
	
	/**
	 * 创建运行植入器
	 */
	createRuntimeWiring: function(assembly){
		var itemsDataFetcher = new ItemsDataFetcher();
		return RuntimeWiring.newRuntimeWiring()
			.type("Query", (typeWiring) => typeWiring
					.dataFetcher("findById", new FindByIdDataFetcher())
					.dataFetcher("getItems", itemsDataFetcher)
					.dataFetcher("getItemsWithExpression", itemsDataFetcher))
			.build();
		
	}
})

//--------------------------------------
//本脚本的输出服务,必须存在的变量及类型要求  (assembly.xml中定义)
//
//变量名           类型
//graphQLModular: com.massyframework.beanskin.graphql.context.RuntimeWiringFactory
//----------------------------------------
var runtimeWiringFactory = new MyRuntimeWiringFactory();
var graphQLModular = new DefaultGraphQLModular();
graphQLModular.setRuntimeWiringFactory(runtimeWiringFactory);
